<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * This is used to send mails.
 *
 * @package   block_email_list
 * @author    Toni Mas <toni.mas@uib.dot.es>
 * @copyright 2009 by <toni.mas at uib dot es>
 * @license   The source code packaged with this file is Free Software, Copyright (C) 2009 by
 *            <toni.mas at uib dot es>.
 *            It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
 *            You can get copies of the licenses here: http://www.affero.org/oagpl.html
 *            AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".
 * @uses      $CFG, $DB, $OUTPUT, $PAGE
 */
require_once('../../../config.php');
require_once($CFG->dirroot.'/blocks/email_list/email/lib.php');

// For apply ajax and javascript functions.
require_once($CFG->libdir. '/ajax/ajaxlib.php');
require_once($CFG->dirroot.'/blocks/email_list/email/email.class.php');

/**
 * Get the html for the contact entry
 *
 * @author Tyler Bannister <tyler.bannister@remote-learner.net>
 * @param Object  $user    The user object
 * @param String  $wwwroot The wwwroot url
 * @param Boolean $ajax    Whether or not we're using AJAX
 * @param String  $type    The type of field (used in fieldname)
 * @return String
 */
function get_contact_html($user, $wwwroot, $ajax=false, $type='to') {

    if ($ajax) {
        $js = array('var input = \'<input type="hidden" value="'.$user->id.'" name="'. $type .'[]">\';',
                    'var rand = get_random();',
                    'var fullname = window.document.createElement("span");',
                    'fullname.setAttribute("id", "id_nameto"+rand);',
                    'fullname.setAttribute("class", "ajax_user_selected");',
                    'window.document.getElementById("id_name'. $type .'").parentNode.insertBefore('
                    .    'fullname,window.document.getElementById("id_name'. $type .'"));',
                    'var htmlimg = "<img class=\"imgdropuser\" src=\"'.$wwwroot
                    .    '/blocks/email_list/email/images/cross.png\" height=\"11\" width=\"11\" alt=\"'
                    .    get_string('remove', 'block_email_list').'\" />";',
                    'fullname.innerHTML = "'.fullname($user) .'<a href=\"#\" onClick=\"'
                    .    'removeAJAXContact(\'id_name'. $type .'"+rand+"\');\">"+htmlimg+input+"</a>";');

    } else {
        $js = array('var contacts = window.document.createElement("span");',
                    'window.document.getElementById(\'id_name'. $type .'\').parentNode.appendChild(contacts);',
                    'contacts.innerHTML = \'<input type="hidden" value="'.$user->id.'" name="'. $type .'[]">\';');
    }

    return implode($js, "\n");
}

global $USER;

$mailid        = optional_param('id', 0, PARAM_INT);                  // email ID
$courseid      = optional_param('course', SITEID, PARAM_INT);         // Course ID
$action        = optional_param('action', '', PARAM_ALPHANUM);        // Action to execute
$folderid      = optional_param('folderid', 0, PARAM_INT);            // folder ID
$folderoldid   = optional_param('folderoldid', 0, PARAM_INT);         // folder ID
$filterid      = optional_param('filterid', 0, PARAM_INT);            // filter ID

$olderrors     = optional_param('error', 0, PARAM_INT);
$subject       = optional_param('subject', '', PARAM_ALPHANUM);       // Subject of mail
$body          = optional_param('body', '', PARAM_ALPHANUM);          // Body of mail

$mails         = optional_param('mails', '', PARAM_ALPHANUM);         // Next and previous mails
$selectedusers = optional_param('selectedusers', '', PARAM_ALPHANUM); // User who send mail

// SSL encription
if ($CFG->email_enable_ssl) {
    $PAGE->https_required();
    $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
} else {
    $wwwroot = $CFG->wwwroot;
}

if (! $course = $DB->get_record('course', array('id' => $courseid))) {
    print_error('invalidcourseid', 'block_email_list');
}

require_login($course->id, false); // No autologin guest

if (! email_is_enabled_email_list($course->id)) {
    print_error('blocknotavailable', 'block_email_list');
}

// CONTRIB-626. Add capability for send messages. Thanks Jeff.
if (! has_capability('block/email_list:sendmessage', $PAGE->context)) {
    print_error('forbiddensendmessage', 'block_email_list',
                $CFG->wwwroot.'/blocks/email_list/email/index.php?id='.$course->id);
}

if (has_capability('block/email_list:editsettings', $PAGE->context)) {
    $preferencesbutton = email_get_preferences_button($courseid);
    $PAGE->set_button($preferencesbutton);
}

$stremail  = get_string('name', 'block_email_list');

$PAGE->set_title("$course->shortname: $stremail");
$PAGE->set_heading($course->fullname);
$PAGE->set_cacheable(true);
$PAGE->set_url("/blocks/email_list/sendmail.php?course={$courseid}&folderid={folderid}");
$PAGE->navbar->add(get_string('nameplural', 'block_email_list'), 'index.php?id='.$course->id);
$PAGE->navbar->add(get_string('name', 'block_email_list'));
$PAGE->requires->css('/blocks/email_list/email/email.css');
$PAGE->requires->css('/blocks/email_list/email/treemenu.css');
$PAGE->requires->css('/blocks/email_list/email/tree.css');
$PAGE->requires->js('/blocks/email_list/email/treemenu.js');
$PAGE->requires->js('/blocks/email_list/email/email.js');

// Options for new mail and new folder
$options = new stdClass();
$options->id = $courseid;
$options->mailid = $mailid;
$options->folderid = $folderid;
$options->filterid = $filterid;
$options->folderoldid = $folderoldid;

// Fields of error mail (only use when created new email and it's insert fail)
$fieldsmail = new stdClass();
$fieldsmail->subject = $subject;
$fieldsmail->body = $body;

// Get actual folder, for show
if (! $folder = email_get_folder($folderid) ) {
    // Default, is inbox
    $folder = new stdClass();
    $folder->name = get_string('inbox', 'block_email_list');
}

require_once('mail_edit_form.php');

// Solve bug
if (!isset($mail)) {
    $mail = new stdClass();
}

if (!isset($mail->body)) {
    $mail->body = '';
}

if (!isset($mail->subject)) {
    $mail->subject = '';
}

/// first create the form
$oldmail  = $DB->get_record('block_email_list_mail', array('id' => $mailid));
$mailform = new mail_edit_form('sendmail.php', array('oldmail' => $oldmail, 'action' => $action),
                               'post', '',array('name' => 'sendmail'));
$script        = '';
$notifications = array();
$draft = false;

if ($mailform->is_cancelled()) {
    // Only redirect
    redirect($CFG->wwwroot.'/blocks/email_list/email/index.php?id='.$courseid, '', '0');

} else if ($form = $mailform->get_data()) {

    if (empty($form->to) && empty($form->cc) && empty($form->bcc) && empty($form->toext)) {
        $notifications[] = $OUTPUT->notification(get_string('nosenders', 'block_email_list'));
        $mailform->set_data($form);

    } else if (! empty($form->send) || ! empty($form->draft)) {

        // Create new eMail
        $email = new eMail();

        // User send mail
        $email->set_writer($USER->id);
        $email->set_course($courseid);

        // Generic URL for send mails errors
        $baseurl = $CFG->wwwroot.'/blocks/email_list/email/index.php?id='.$courseid.'&amp;mailid='
                 . $form->id.'&amp;subject=\''.$form->subject.'\'&amp;body=\''.$form->body.'\'';

        // Add subject
        $email->set_subject($form->subject);

        // Get upload files
        $email->set_attachments(isset($form->attachments) ? $form->attachments : null);

        // If forward or draft mail, can do old attachments
        $i = 0;
        $oldattach = 'oldattachment'.$i;

        if (isset($form->$oldattach)) {
            $attachments = array();

            while (true) {
                $oldattachck = $oldattach.'ck';

                // Only add if it is checked
                if (isset($form->$oldattachck) && $form->$oldattachck) {
                    $attachments[] = $form->$oldattach;
                }
                $i++;
                $oldattach = "oldattachment$i";

                if (empty($form->$oldattach)) {
                    break;
                }
            }

            $email->set_oldattachments($attachments);
        }

        // Add body
        $email->set_body($form->body);

        // Add users sent mail
        if (isset($form->to)) {
            $email->set_sendusersbyto($form->to);
        }

        if (isset($form->cc)) {
            $email->set_sendusersbycc($form->cc);
        }

        if (isset($form->bcc)) {
            $email->set_sendusersbybcc($form->bcc);
        }

        // Add type action and if corresponding old mail id.
        $email->set_type($form->action);
        $email->set_oldmailid((isset($form->oldmailid) ) ? $form->oldmailid : null);
        $email->set_responded((isset($form->respondedid) and $form->respondedid > 0) ? $form->respondedid :
                (isset($form->oldmailid) ? $form->oldmailid : 0)); // Change oldmail to responded.
        $email->set_mailid((isset($form->id) ) ? $form->id : null);

        // Add new mail, in the Inbox or corresponding folder
        if (empty($form->draft)) {

            if (isset($form->action) && ($form->action == EMAIL_FORWARD)) {
                $form->oldmailid = null;    // Drop mailid on forward
            }

            if (! $email->send()) {
                $notifications[] = $OUTPUT->notification(get_string('mailnotsent', 'block_email_list'));
            }

            // Send external emails if required
            if (!empty($form->toext)) {
                $toaddrs = explode(',', $form->toext);
                $errorstr = '';

                $success = sendmail_external($toaddrs, $USER, $email->subject, $email->body,
                                             $email->get_attachments(), $errorstr);

                if (! $success) {
                    // send external failed
                    add_to_log($email->course, 'email_list', 'send ext.', '',
                               "ERROR: {$errorstr}", 0, $email->userid);
                    print_error('failsendext', 'block_email_list',
                                "{$CFG->wwwroot}/blocks/email_list/email/sendmail.php?");
                } else {
                    // send external ok, insert into table
                    if (! insert_external_list_send($email, $form->toext)) {
                        print_error('failinsertrecord', 'block_email_list',
                                    "{$CFG->wwwroot}/blocks/email_list/email/sendmail.php?");
                    }
                }
            }
        } else {
            // Save in Draft

            // Fix forward bug. Thanks Ann
            if (isset($form->action)) {

                if ($form->action == EMAIL_FORWARD) {
                    $form->oldmailid = null; // Drop mailid on forward
                }

                // CONTRIB-702
                if ($form->action == EMAIL_REPLY or $form->action == EMAIL_REPLYALL or $form->action == EMAIL_FORWARD) {
                    unset($form->id); // If you don't unset id, save eMail update this record.
                }
            }

            if (! $email->save((isset($form->id) ) ? $form->id : null)) {
                $notifications[] = $OUTPUT->notification(get_string('dontsavemailindraft', 'block_email_list'));
            }
        }

        if ( empty($form->draft) ) {
            $legend = get_string('sendok', 'block_email_list');
        } else {
            $legend = get_string('draftok', 'block_email_list');
        }

        redirect($CFG->wwwroot.'/blocks/email_list/email/index.php?id='.$courseid, $legend, '4');

    } else {
        print_error('failsendordraftmail', 'block_email_list');
    }

} else {
    // DRAFT integration
    $draft = true;

    // Prepare mail according action

    if ($action == EMAIL_REPLY || $action == EMAIL_REPLYALL || $action == EMAIL_EDITDRAFT) {

        if (! $mail = $DB->get_record('block_email_list_mail', array('id' => $mailid))) {
            print_error(get_string('cannotfindmail', 'block_email_list'));
        }
    }

    $nosenders = false;
    $nosubject = false;
    $formoldattachments = false;

    if ($action == EMAIL_FORWARD) {
        // Clear selected users
        $selectedusers = array();
    }

    if ($action == EMAIL_REPLY) {
        // Predefinity user send
        $user = email_get_user($mailid);
        $mail->nameto = email_fullname($user, $PAGE->context);
    }

    if ($action == EMAIL_REPLYALL) {

        $selectedusers = array();
        // Predefinity user send
        $userwriter = email_get_user($mailid);

        // First, prepare writer
        $selectedusers[] = $userwriter->id;

        // Get users sent mail, with option for reply all
        $selectedusersto = $selectedusers;
        $mailtos = array();

        foreach ($selectedusersto as $userid) {
            $mailtos[] = email_fullname($DB->get_record('user', array('id'=> $userid)), $PAGE->context);
        }
        $mail->nameto = implode(', ', $mailtos);

        // Get users sent mail, with option for reply all
        $selecteduserscc = array_merge(email_get_users_sent($mailid, true, $userwriter, 'to'),
                                       email_get_users_sent($mailid, true, $userwriter, 'cc'));
        $mailccs = array();

        foreach ($selecteduserscc as $userid) {
            $mailccs[] = email_fullname($DB->get_record('user', array('id'=> $userid)), $PAGE->context);
        }
        $mail->namecc = implode(', ', $mailccs);
    }

    if ($action == EMAIL_FORWARD) {
        $newmail = new stdClass();

        // Get mail
        if (! $oldmail = $DB->get_record('block_email_list_mail', array('id' => $mailid))) {
            print_error('cannotfindmail', 'block_email_list');
        }

        $newmail = (PHP_VERSION < 5) ? $oldmail : clone($oldmail);

        // Remove id
        unset($newmail->id);
        $newmail->mailid = null;

        // Predefinity user send
        $user = email_get_user($mailid);
    }

    if ($action == EMAIL_EDITDRAFT) {
        // Predefinity user send
        $userwriter = email_get_user($mailid);

        // Get users sent mail, with option for reply all
        $selectedusersto = email_get_users_sent($mailid, true, false, 'to');

        $mailtos = array();

        foreach ($selectedusersto as $userid) {
            $mailtos[] = email_fullname($DB->get_record('user', array('id' => $userid)), $PAGE->context);
        }
        $mail->nameto = implode(', ', $mailtos);

        // Get users sent mail, with option for reply all
        $selecteduserscc = email_get_users_sent($mailid, true, false, 'cc');

        $mailccs = array();

        foreach ($selecteduserscc as $userid) {
            $mailccs[] = email_fullname($DB->get_record('user', array('id' => $userid)), $PAGE->context);
        }
        $mail->namecc = implode(', ', $mailccs);

        // Get users sent mail, with option for reply all
        $selectedusersbcc = email_get_users_sent($mailid, true, false, 'bcc');

        $mailbccs = array();

        foreach ($selectedusersbcc as $userid) {
            $mailbccs = email_fullname($DB->get_record('user', array('id' => $userid)), $PAGE->context);
        }
        $mail->namebcc = implode(', ', $mailbccs);
    }

    if ($action == EMAIL_REPLY || $action == EMAIL_REPLYALL) {
        // Modify subject
        $mail->subject = get_string('re', 'block_email_list').' '.$mail->subject;
    }

    if ($action == EMAIL_FORWARD) {
        // Modify subject
        $newmail->subject = get_string('fw', 'block_email_list').' '.$oldmail->subject;
    }

    if ($action == EMAIL_REPLY || $action == EMAIL_REPLYALL) {
        // Separe message in diferents lines, who add >
        $lines = explode('<br />', $mail->body);

        (isset($user)) ? $userdef = $user : $userdef = $userwriter;

        // Insert default line for known sended mail, and date
        $body =  email_make_default_line_replyforward($userdef, $mail->timecreated, $PAGE->context);
        // Intert >
        foreach ($lines as $line) {
            $body = $body. '>' .$line. '<br />'."\n";
        }
        // Assign new body
        $mail->body = $body;
    }

    if ($action == EMAIL_FORWARD) {
        // Separate message into diferent lines and add >
        $lines = explode('<br />', $newmail->body);

        // Insert default line for known sended mail, and date
        $body =  email_make_default_line_replyforward($user, $newmail->timecreated, $PAGE->context);

        // Intert >
        foreach ($lines as $line) {
            $body = $body. '>' .$line. '<br />'."\n";
        }
        // Assign new body
        $newmail->body = $body;

        // Add oldmail
        $newmail->oldmail = $mailid;
    }

    $activemail = $mail;
    if ( $action == EMAIL_FORWARD ) {
        $activemail = $newmail;
    }

    if ( $action == EMAIL_REPLY || $action == EMAIL_REPLYALL ) {
        $activemail->action = EMAIL_REPLY;
    }

    $mailform->focus('subject');
    if (($action == EMAIL_REPLY) || ($action == EMAIL_REPLYALL) || ($action == EMAIL_FORWARD)) {
        $logactions = array(EMAIL_REPLY => 'reply', EMAIL_REPLYALL => 'reply all', EMAIL_FORWARD => 'forward');

        // Add log
        add_to_log($activemail->course, 'email_list', $logactions[$action], '',
                  "$activemail->subject", 0, $activemail->userid);
        $mailform->focus('body');
    }
    $mailform->set_data($activemail);

    $email_enable_ajax = isset($CFG->email_enable_ajax) ? $CFG->email_enable_ajax : 0;

    if ($action == EMAIL_REPLY) {
        $script .= '<script type="text/javascript" language="JavaScript">'
                 . get_contact_html($user, $wwwroot, $email_enable_ajax)
                 . '</script>';
    }

    if (($action == EMAIL_REPLYALL) || ($action == EMAIL_EDITDRAFT)) {
        $script .= ' <script type="text/javascript" language="JavaScript">';

        foreach ($selectedusersto as $selecteduser) {
            $tempuser = $DB->get_record('user', array('id' => $selecteduser));
            $script .= get_contact_html($tempuser, $wwwroot, $email_enable_ajax);
        }

        foreach ($selecteduserscc as $selecteduser) {
            $tempuser = $DB->get_record('user', array('id' => $selecteduser));
            $script .= get_contact_html($tempuser, $wwwroot, $email_enable_ajax, 'cc');
        }

        if ($action == EMAIL_EDITDRAFT) {

            foreach ($selectedusersbcc as $selecteduser) {
                $tempuser = $DB->get_record('user', array('id' => $selecteduser));
                $script .= get_contact_html($tempuser, $wwwroot, $email_enable_ajax, 'bcc');
            }
        }

        $script .= '</script>';
    }
}

echo $OUTPUT->header();

/// Print the main part of the page

// Print principal table. This have 2 columns . . .  and possibility to add right column.
echo '<table id="layout-table">
              <tr>';


// Print "blocks" of this account
echo '<td style="width: 180px;" id="left-column">';
email_printblocks($USER->id, $courseid);

// Close left column
echo '</td>';

// Print principal column
echo '<td id="middle-column">';

// Print middle table
echo $OUTPUT->heading(get_string('mailbox', 'block_email_list'). ': '. $folder->name);

echo '<div>&#160;</div>';


// Print tabs options
email_print_tabs_options($courseid, $folderid, $action);

echo implode("\n", $notifications);

$mailform->display();


// Close principal column
echo '</td>';

// Close table
echo "</tr>\n</table>\n";

// Print autocomplete javascript (if required)
$ajaxenabled = ajaxenabled(isset($CFG->ajaxtestedbrowsers) ? $CFG->ajaxtestedbrowsers : null);

$email_enable_ajax = isset($CFG->email_enable_ajax) ? $CFG->email_enable_ajax : 0;

if ($draft && $email_enable_ajax && $ajaxenabled) {
    include_once($CFG->dirroot .'/blocks/email_list/email/participants/yui_autocomplete.html');
}

echo $script;

echo $OUTPUT->footer();
